#!/usr/bin/env ruby

##
# Copyright (C) 2014 Hai Bison
#
# See the file LICENSE at the root directory of this project for copying
# permission.

require 'optparse'
require 'ostruct'

DESCRIPTION = "
         *** CRUNCH v3.0.1 (r7) ***

Usage:

    $ #{File.basename($0)} <root-directory>

Where <root-directory> is the root directory of your Android project. It should
contain `AndroidManifest.xml`.

This script deletes all `crunch` directories of Eclipse projects. While using
Ant to build the project, it'll fail to handle those directories.

Note that this script automatically handles sub projects as well. All you need
to do is provide the root directory of parent project.
"

REGEX_LIBRARY = /^android\.library\.reference\.[0-9]+=/
FILENAME_PROJECT_PROPERTIES = "project.properties"

##
# Cleans up `bin/res/crunch` inside `pathname`.
#
# Parses `project.properties` inside `pathname`, browses to sub projects and
# cleans up their `bin/res/crunch` by `rm -Rf`.
#
# `handled_dirs` is list of already handled directories to keep track of.
#
def handle_dir pathname, handled_dirs=[]
    project_properties = File.join pathname, FILENAME_PROJECT_PROPERTIES
    if ! File.file? project_properties
        puts " ! `#{FILENAME_PROJECT_PROPERTIES}` not found"
        return
    end

    crunch_dir = File.join pathname, 'bin', 'res', 'crunch'
    return if handled_dirs.include? crunch_dir
    handled_dirs << crunch_dir

    if File.directory? crunch_dir
        puts "\t> Cleaning up: '%s'" % crunch_dir
        system('rm', '-Rf', crunch_dir)
    else
        puts "\t> Not found  : '%s'" % crunch_dir
    end

    File.open(project_properties, 'r').each_line do |line|
        if line =~ REGEX_LIBRARY
            code_dir = File.absolute_path(
                File.join pathname, line.sub(REGEX_LIBRARY, '').strip)
            handle_dir code_dir, handled_dirs
        end
    end
end # handle_dir

if __FILE__ == $0
    # Parser
    args = OptionParser.new do |opts|
        opts.banner = DESCRIPTION
        opts.separator ''
        opts.separator 'Specific options:'

        opts.on('-h', '--help', "Print help message.") do
            puts opts
            exit
        end
    end.parse! ARGV.clone

    if args.empty?
        puts " > No root directory specified, considering current one..."
        handle_dir Dir.pwd
    else
        handled_dirs = []
        args.each do |dir|
            if File.directory? dir
                handle_dir dir, handled_dirs
            else
                puts " ! Directory not existed '#{dir}'"
            end
        end # for each argument
    end
end # __FILE__ == $0